package com.shcz.migu.api;


import android.text.TextUtils;

import com.shcz.migu.local_setting.LocalConstants;
import com.shcz.migu.observe.base_observe.ConstObserver;
import com.shcz.migu.observe.login_observe.LoginObserverService;
import com.shcz.migu.resp.base.ResponseInfo;
import com.shcz.migu.utils.Constants;
import com.shcz.migu.utils.LogUtil;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;


public abstract class ApiCallback<M> extends Subscriber<M> {

    public abstract void onSuccess(M model);

    public abstract void onFailure(String msg);

//    public abstract void onNoNetWorkFailure(String msg);

    public abstract void onFinish();

    public void onBegin() {
    }

    @Override
    public void onStart() {
        super.onStart();
        onBegin();
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            //httpException.response().errorBody().string()
            int code = httpException.code();
            String msg = httpException.getMessage();
            LogUtil.d("code=" + code);
            if (code == 504) {
                msg = "网络不给力";
            }
            if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试";
            }
            onFailure(msg);
        } else {
            onFailure(e.getMessage() + LocalConstants.NETWORK_FLAG);
        }
        onFinish();
    }

    @Override
    public void onNext(M model) {
        ResponseInfo baseInfo = (ResponseInfo) model;
        if (baseInfo.getError() != null) {
            String msg = "网络请求错误";
            if (!TextUtils.isEmpty(baseInfo.getError().getMsg())) {
                if (baseInfo.getError().getCode() == Constants.INVAID_TOKEN)//会话过期
                {
                    LoginObserverService.getInstance().notifyDataChanged(ConstObserver.LOGIN_INVIAD_TOKEN);
                    return;
                }
                msg = baseInfo.getError().getMsg();
            }
            onFailure(msg);
        } else
            onSuccess(model);

    }

    @Override
    public void onCompleted() {
        onFinish();
    }
}
